#!/bin/bash

# Ubuntu桌面环境 - Linux快速测试脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_message() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_header() {
    echo -e "${BLUE}================================${NC}"
    echo -e "${BLUE}  Ubuntu桌面环境快速测试${NC}"
    echo -e "${BLUE}================================${NC}"
}

# 检查Docker
check_docker() {
    if ! command -v docker &> /dev/null; then
        print_error "Docker未安装，请先安装Docker"
        exit 1
    fi
    
    if ! docker info &> /dev/null; then
        print_error "Docker服务未运行，请启动Docker服务"
        exit 1
    fi
    
    print_message "Docker检查通过"
}

# 清理之前的容器
cleanup_previous() {
    print_message "清理之前的容器和镜像..."
    
    # 停止并删除容器
    docker-compose -f docker-compose.lightweight.yml down --rmi all --volumes --remove-orphans 2>/dev/null || true
    docker-compose down --rmi all --volumes --remove-orphans 2>/dev/null || true
    
    # 清理未使用的资源
    docker system prune -f
    
    print_message "清理完成"
}

# 构建轻量级镜像
build_lightweight() {
    print_message "构建轻量级Docker镜像..."
    
    docker-compose -f docker-compose.lightweight.yml build --no-cache
    
    if [ $? -ne 0 ]; then
        print_error "构建失败"
        exit 1
    fi
    
    print_message "轻量级镜像构建成功"
}

# 启动轻量级容器
start_lightweight() {
    print_message "启动轻量级容器..."
    
    docker-compose -f docker-compose.lightweight.yml up -d
    
    if [ $? -ne 0 ]; then
        print_error "启动失败"
        exit 1
    fi
    
    print_message "轻量级容器启动成功"
}

# 等待容器就绪
wait_for_container() {
    print_message "等待容器就绪..."
    
    local max_attempts=30
    local attempt=1
    
    while [ $attempt -le $max_attempts ]; do
        if docker ps | grep -q "ubuntu-desktop-lightweight"; then
            local status=$(docker inspect --format='{{.State.Status}}' ubuntu-desktop-lightweight 2>/dev/null)
            if [ "$status" = "running" ]; then
                print_message "容器运行正常"
                return 0
            fi
        fi
        
        echo -n "."
        sleep 2
        attempt=$((attempt + 1))
    done
    
    print_error "容器启动超时"
    return 1
}

# 检查容器状态
check_container_status() {
    print_message "检查容器状态..."
    
    docker-compose -f docker-compose.lightweight.yml ps
    
    echo
    print_message "容器详细信息："
    docker inspect ubuntu-desktop-lightweight --format='{{.Name}} - {{.State.Status}} - {{.State.Running}}'
}

# 查看容器日志
show_container_logs() {
    print_message "查看容器日志..."
    
    docker-compose -f docker-compose.lightweight.yml logs --tail=20
}

# 测试桌面快捷方式
test_desktop_shortcuts() {
    print_message "测试桌面快捷方式..."
    
    echo "桌面快捷方式列表："
    docker exec -it ubuntu-desktop-lightweight ls -la /home/ubuntu/Desktop/
    
    echo
    echo "快捷方式内容示例："
    docker exec -it ubuntu-desktop-lightweight cat /home/ubuntu/Desktop/mousepad.desktop
}

# 测试网络连接
test_network() {
    print_message "测试网络连接..."
    
    echo "容器网络配置："
    docker exec -it ubuntu-desktop-lightweight ip addr show
    
    echo
    echo "测试网络连通性："
    docker exec -it ubuntu-desktop-lightweight ping -c 3 8.8.8.8
}

# 显示访问信息
show_access_info() {
    echo
    echo -e "${GREEN}================================${NC}"
    echo -e "${GREEN}  轻量级桌面环境测试成功！${NC}"
    echo -e "${GREEN}================================${NC}"
    echo
    
    echo "访问方式："
    echo "  VNC访问: localhost:5901"
    echo "  SSH访问: ssh -p 2223 ubuntu@localhost"
    echo
    
    echo "本地X11显示（Linux特有）："
    echo "  1. 允许X11连接: xhost +local:docker"
    echo "  2. 启动桌面: docker exec -it ubuntu-desktop-lightweight startxfce4"
    echo
    
    echo "测试命令："
    echo "  查看状态: docker-compose -f docker-compose.lightweight.yml ps"
    echo "  查看日志: docker-compose -f docker-compose.lightweight.yml logs -f"
    echo "  进入容器: docker exec -it ubuntu-desktop-lightweight bash"
    echo "  停止服务: docker-compose -f docker-compose.lightweight.yml down"
    echo
}

# 性能测试
performance_test() {
    print_message "执行性能测试..."
    
    echo "容器资源使用情况："
    docker stats ubuntu-desktop-lightweight --no-stream
    
    echo
    echo "系统资源使用情况："
    echo "内存使用："
    free -h
    
    echo
    echo "磁盘使用："
    df -h .
    
    echo
    echo "CPU使用："
    top -bn1 | grep "Cpu(s)" | awk '{print $2}' | awk -F'%' '{print $1}'
}

# 主函数
main() {
    print_header
    
    # 检查Docker
    check_docker
    
    # 清理之前的容器
    cleanup_previous
    
    # 构建镜像
    build_lightweight
    
    # 启动容器
    start_lightweight
    
    # 等待容器就绪
    if wait_for_container; then
        # 检查状态
        check_container_status
        
        # 查看日志
        show_container_logs
        
        # 测试功能
        test_desktop_shortcuts
        test_network
        
        # 性能测试
        performance_test
        
        # 显示访问信息
        show_access_info
        
        print_message "测试完成！"
    else
        print_error "测试失败，请检查日志"
        docker-compose -f docker-compose.lightweight.yml logs
        exit 1
    fi
}

# 捕获信号
trap 'print_error "脚本被中断"; exit 1' INT TERM

# 运行主函数
main "$@" 